package demo.huodongbaoming.service.impl;

import demo.huodongbaoming.service.FileStorageService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.UUID;

@Service
public class FileStorageServiceImpl implements FileStorageService {

    @Value("${file.upload-dir}")
    private String uploadDir;

    private Path fileStorageLocation;

    @PostConstruct
    public void init() {
        this.fileStorageLocation = Paths.get(uploadDir).toAbsolutePath().normalize();
        try {
            Files.createDirectories(this.fileStorageLocation);
        } catch (IOException e) {
            throw new RuntimeException("无法创建文件上传目录", e);
        }
    }

    @Override
    public String storeFile(MultipartFile file) {
        // 获取文件名
        String originalFileName = StringUtils.cleanPath(file.getOriginalFilename());
        
        // 生成唯一文件名
        String fileName = UUID.randomUUID().toString() + "_" + originalFileName;
        
        try {
            // 检查文件名是否包含无效字符
            if (fileName.contains("..")) {
                throw new RuntimeException("文件名包含无效路径序列：" + fileName);
            }
            
            // 复制文件到目标位置
            Path targetLocation = this.fileStorageLocation.resolve(fileName);
            Files.copy(file.getInputStream(), targetLocation, StandardCopyOption.REPLACE_EXISTING);
            
            return fileName;
        } catch (IOException e) {
            throw new RuntimeException("无法存储文件 " + fileName, e);
        }
    }

    @Override
    public Path getFilePath(String fileName) {
        return this.fileStorageLocation.resolve(fileName);
    }
} 